package com.example.aigc_education.integration.response.workflows.v1;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Data;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

@Data
public class CozeWebSearchResponse implements Serializable {

    @JsonProperty("content_type")
    private Integer content_type;

    @JsonDeserialize(using = WebSearchDataDeserializer.class)
    private WebSearchData data;

    @JsonProperty("original_result")
    private Object original_result;

    @JsonProperty("type_for_model")
    private Integer type_for_model;


    @Data
    public static class WebSearchData implements Serializable{
        private String summary;

        private List<Url> urls;
    }

    @Data
    public static class Url implements Serializable{
        private String title;
        private String link;
        private String summary;
    }

    public static class WebSearchDataDeserializer extends JsonDeserializer<WebSearchData> {
        @Override
        public CozeWebSearchResponse.WebSearchData deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            ObjectMapper mapper = (ObjectMapper) p.getCodec();
            JsonNode node = p.readValueAsTree();
            CozeWebSearchResponse.WebSearchData webSearchData = new CozeWebSearchResponse.WebSearchData();

            if (node.isTextual()) {
                String jsonString = node.asText();
                webSearchData = mapper.readValue(jsonString, mapper.getTypeFactory().constructType(CozeWebSearchResponse.WebSearchData.class));
            }

            return webSearchData;
        }
    }
}
